from datetime import datetime, timezone, timedelta
import requests
from flask import views
from flask import request
from flask import Blueprint
from pymongo import MongoClient
from flask import make_response
from bson import ObjectId
import json

tools_bp = Blueprint("tools", __name__, url_prefix='/tools')


class IPView(views.MethodView):
    def get(self):
        ip = request.remote_addr
        rst = make_response(json.dumps({'data': {"ip": ip}}, ensure_ascii=False))
        rst.headers['Access-Control-Allow-Origin'] = '*'
        return rst, 200


class IPCityView(views.MethodView):
    def get(self):
        ip = request.remote_addr
        res = requests.get(url="https://ip.taobao.com/outGetIpInfo?ip={}&accessKey=alibaba-inc".format(ip))

        rst = make_response(res.content)
        rst.headers['Access-Control-Allow-Origin'] = '*'
        return rst, 200


class Weather(views.MethodView):
    def get(self, city):
        client = MongoClient('ledemon.cn', 27017)
        db = client.admin
        db.authenticate("ledemon", "a5910162", mechanism='SCRAM-SHA-1')
        weather_db = client.weather_pause
        collection = weather_db.weather
        city_query = {"city": city}
        city_list = collection.find(city_query)

        result = [doc for doc in city_list]
        res_arr = []
        for item in result:
            item["id"] = str(ObjectId(item["_id"]))
            del item["_id"]
            cre_time = item["time"]
            cre_time.replace(tzinfo=timezone.utc)
            cn_dt = cre_time.astimezone(timezone(timedelta(hours=16)))
            item["time"] = cn_dt.strftime('%Y-%m-%d %H:%M:%S')
            res_arr.append(item)
        # print(res_arr)
        rst = make_response(json.dumps({'data': res_arr}, ensure_ascii=False))
        rst.headers['Access-Control-Allow-Origin'] = '*'
        rst.headers['Content-Type'] = 'application/json;charset=utf-8'
        return rst, 200


tools_bp.add_url_rule("/city/", view_func=IPCityView.as_view('ip_city'))
tools_bp.add_url_rule("/ipaddress/", view_func=IPView.as_view('ip_address'))
tools_bp.add_url_rule("/weather/<string:city>/", view_func=Weather.as_view('city_weather'))
